package com.ysstech.reportworld.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.reportworld.entity.DemandBugInfo;
import com.ysstech.reportworld.entity.Table;
import com.ysstech.reportworld.entity.TableDetail;
import com.ysstech.reportworld.entity.TpGlExhibDatadict;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2022-04-27
 */
@Controller
@Slf4j
@Api(tags = "报表世界表明细信息管理api")
@RequestMapping("/tableDetail")
public class TableDetailController extends BaseController {

    @Autowired
    private TableDetailService tableDetailService;
    @Autowired
    private DemandBugInfoService demandBugInfoService;
    @Autowired
    private ModularService modularService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private TableService tableService;
    // 基础数据的字典信息
    @Autowired
    private TpGlExhibDatadictService tpGlExhibDatadictService;

    /**
     * 表世界表结构明细信息页面
     *
     * @return
     * @throws Exception
     */
    @YssPermissions(value = {"reportworld:tableDetail"})
    @ApiOperation(value = "跳转表明细信息管理页面")
    @YssLog(module = "报表世界表明细信息管理", remark = "跳转表明细信息管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "reportworld/tableDetail";
    }

    @YssPermissions(value = {"reportworld:tableDetail"})
    @YssLog(module = "报表世界表明细信息管理", remark = "查询报表世界表结构明细信息")
    @ApiOperation(value = "查询报表世界表结构明细信息")
    @RequestMapping(value = "/queryAllDataTableDetail")
    @ResponseBody
    public RestResult queryAllDataTableDetail(TableDetail tableDetail, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("查询报表世界表结构明细信息成功",
                tableDetailService.queryAllDataTableDetail(tableDetail, this.getPage(page, rows)));
    }

    @YssPermissions(value = {"reportworld:tableDetail"})
    @ApiOperation(value = "获取报表世界表结构明细信息管理页面初始值")
    @YssLog(module = "报表世界表明细信息管理", remark = "获取报表世界表结构明细信息管理页面初始值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        //字段类型
        List<Dicvalue> listColumnType = dicValueService.getCacheDicValueList(ReportWorldEnum.COLUMN_TYPE.getCode());
        map.put("listColumnType", listColumnType);
        map.put("listColumnType2", listColumnType);
        // 报表世界所在分层
        List<Dicvalue> listLayered = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_TABLE_LAYERED.getCode());
        map.put("listLayered", listLayered);
        map.put("listLayered2", listLayered);
        // 状态
        List<Dicvalue> listStatus = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_STATUS.getCode());
        map.put("listStatus", listStatus);
        map.put("listStatus2", listStatus);
        // 所属模块
        List<TreeNode> listModular = modularService.queryModularTree();
        map.put("listModular", listModular);
        // 字段所属客户
        List<TreeNode> listCustomer = customerService.queryCustomerTree();
        map.put("listCustomer", listCustomer);
        // 字段所属报表
        List<TreeNode> listReport = reportService.queryReportTree();
        map.put("listReport", listReport);
        // 版本
        List<Dicvalue> listVersion = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_VERSION.getCode());
        map.put("listVersion", listVersion);
        map.put("listVersion2", listVersion);
        // 表类型
        List<Dicvalue> listFtype = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_TABLE_FTYPE.getCode());
        map.put("listFtype", listFtype);
        map.put("listFtype2", listFtype);
        // 表来源
        List<Dicvalue> listFsource = dicValueService.getCacheDicValueList(ReportWorldEnum.REPORT_TABLE_FSOURCE.getCode());
        map.put("listFsource", listFsource);
        map.put("listFsource2", listFsource);
        // 查询所有字典项信息的语句
        QueryWrapper<TpGlExhibDatadict> wrapper = new QueryWrapper<>();
        wrapper.select("CLASS_ID,CLASS_NAME");
        wrapper.groupBy("CLASS_ID");
        wrapper.orderByAsc("CLASS_ID");
        List<TpGlExhibDatadict> listTpGlExhibDatadict = tpGlExhibDatadictService.list(wrapper);
        if (!CollectionUtils.isEmpty(listTpGlExhibDatadict)) {
            for (TpGlExhibDatadict tpGlExhibDatadict : listTpGlExhibDatadict) {
                if (null == tpGlExhibDatadict) {
                    continue;
                }
                tpGlExhibDatadict.setClassName(tpGlExhibDatadict.getClassId() + "-" + tpGlExhibDatadict.getClassName());
            }
        }
        map.put("listTpGlExhibDatadict", listTpGlExhibDatadict);
        map.put("listTpGlExhibDatadict2", listTpGlExhibDatadict);
        // 当前版本的所有需求和BUG
        List<DemandBugInfo> demandBugInfoList = demandBugInfoService.selectByPrimaryByVersion();
        map.put("demandBugInfoList", demandBugInfoList);
        QueryWrapper<Table> wrapper2 = new QueryWrapper<>();
        List<Table> tables = tableService.list(wrapper2);
        if (!CollectionUtils.isEmpty(tables)) {
            for (Table table : tables) {
                if (null == table) {
                    continue;
                }
                table.setChineseName(table.getName() + "-" + table.getChineseName());
            }
        }
        map.put("reportTables", tables);
        map.put("reportTables2", tables);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }


    @YssLog(module = "报表世界表明细信息管理", remark = "添加表结构明细")
    @ApiOperation(value = "添加表结构明细数据")
    @RequestMapping(value = "/add")
    @ResponseBody
    public RestResult add(TableDetail tableDetail) throws Exception {
        if (null == tableDetail) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        tableDetail.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        tableDetail.setAddTime(LocalDateTime.now());
        tableDetailService.addReportTableDetail(tableDetail);
        return ResultGenerator.getSuccessResult("添加表结构明细信息成功");
    }


    @YssLog(module = "报表世界表明细信息管理", remark = "修改报表世界表结构明细")
    @ApiOperation(value = "修改表结构明细数据")
    @RequestMapping(value = "/edit")
    @ResponseBody
    public RestResult edit(TableDetail tableDetail) throws Exception {
        if (null == tableDetail) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        tableDetail.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        tableDetail.setEditTime(LocalDateTime.now());
        tableDetailService.updateReportTableDetail(tableDetail);
        return ResultGenerator.getSuccessResult("修改表结构明细信息成功");
    }

    @YssLog(module = "报表世界表明细信息管理", remark = "删除报表世界表结构明细")
    @ApiOperation(value = "删除报表世界表结构明细数据")
    @RequestMapping(value = "/del")
    @ResponseBody
    public RestResult del(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        tableDetailService.delReportTableDetail(id);
        return ResultGenerator.getSuccessResult("删除报表世界表结构信息成功");
    }

    /**
     * 批量修改表字段信息
     *
     * @param tableDetail
     * @return
     */
    @YssPermissions(value = {"reportworld:tableDetail:batchUpdate"})
    @ApiOperation(value = "批量修改字段值信息")
    @YssLog(module = "报表世界表明细信息管理", remark = "批量修改字段值信息")
    @RequestMapping(value = "/batchUpdateTableInfoDetail")
    @ResponseBody
    public RestResult batchUpdateTableInfoDetail(TableDetail tableDetail, String ids) throws Exception {
        tableDetail.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        tableDetail.setEditTime(LocalDateTime.now());
        tableDetailService.batchUpdateTableInfoDetail(tableDetail, ids);
        return ResultGenerator.getSuccessResult("批量修改字段值信息成功");
    }


    /**
     * 判断用户登录名称是否已经存在
     *
     * @param tableDetail
     * @return
     */
    @ApiOperation(value = "检查表字段名是否存在")
    @YssLog(module = "报表世界表明细信息管理", remark = "检查表名字段是否存在")
    @RequestMapping(value = "/checkColumnName")
    @ResponseBody
    public RestResult checkColumnName(TableDetail tableDetail) {
        if (null == tableDetail || StringUtils.isBlank(tableDetail.getColumnName())
                || StringUtils.isBlank(tableDetail.getTableId())) {
            return ResultGenerator.getFailResult("检查用表字段信息失败，请稍后重试！");
        }
        QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("COLUMN_NAME", tableDetail.getColumnName().toUpperCase());
        wrapper.eq("TABLE_ID", tableDetail.getTableId().toUpperCase());
        int count = tableDetailService.count(wrapper);
        //查询是否存在code值得参数
        if (count > 0) {//返回true表示已经存在
            return ResultGenerator.getSuccessResult("检查表字段信息成功", false);
        } else {
            return ResultGenerator.getSuccessResult("检查表字段信息成功", true);
        }
    }


    /**
     * 保存顺序
     *
     * @param tableDetail
     * @return
     */
    @YssPermissions(value = {"reportworld:table:detail:sequence"})
    @ApiOperation(value = "批量修改字段顺序信息")
    @YssLog(module = "报表世界表明细信息管理", remark = "批量修改字段顺序信息")
    @RequestMapping(value = "/updateTableDetailSequence")
    @ResponseBody
    public RestResult updateTableDetailSequence(String tableDetail) throws Exception {
        if (StringUtils.isBlank(tableDetail)) {
            throw new BusinessException("获取表明细信息失败，请稍后重试！");
        }
        List<TableDetail> listTableDetail = JSONArray.parseArray(tableDetail, TableDetail.class);
        if (CollectionUtils.isEmpty(listTableDetail)) {
            throw new BusinessException("获取表明细信息失败，请稍后重试！");
        }
        tableDetailService.updateBatchById(listTableDetail);
        return ResultGenerator.getSuccessResult("批量修改字段值信息成功");
    }

}
